<template>
  <div class="content">
    <a-card :bordered="false">
      <div
        style="
          display: flex;
          justify-content: flex-start;
          align-items: center;
          height: 50px;
          width: 78%;
        "
      >
        <a-button type="primary" ghost @click="backToGoods">
          <ArrowLeftOutlined />返回
        </a-button>
      </div>
      <a-form ref="formRef" :model="goods" :rules="rules" layout="inline">
        <a-form-item
          style="margin-top: 30px"
          ref="name"
          label="名称"
          name="name"
          :labelCol="{ span: 5 }"
        >
          <a-input
            placeholder="商品全称"
            maxlength="35"
            v-model:value="goods.name"
            size="large"
          />
        </a-form-item>
        <a-form-item
          style="margin-top: 30px"
          ref="price"
          label="单价"
          name="price"
          :labelCol="{ span: 5 }"
        >
          <a-input-number
            v-model:value="goods.price"
            size="large"
            type="number"
            style="width: 258px"
            placeholder="单个商品的价格"
          />
        </a-form-item>
        <a-form-item
          style="margin-top: 30px"
          ref="number"
          label="库存"
          name="number"
          :labelCol="{ span: 5 }"
        >
          <a-input-number
            v-model:value="goods.number"
            size="large"
            style="width: 258px"
            type="number"
            placeholder="商品的数量"
          />
        </a-form-item>
        <a-form-item
          style="margin-top: 30px"
          ref="unit"
          label="单位"
          name="unit"
          :labelCol="{ span: 5 }"
        >
          <a-input
            placeholder="如 个/套/件"
            maxlength="10"
            v-model:value="goods.unit"
            size="large"
          />
        </a-form-item>
        <a-form-item
          style="margin-top: 30px"
          ref="store"
          label="店铺"
          name="store"
          :labelCol="{ span: 5 }"
        >
          <a-select
            v-model:value="goods.store"
            size="large"
            style="width: 258px"
            :options="stores"
          ></a-select>
        </a-form-item>
        <a-form-item
          style="margin-top: 30px"
          ref="category"
          label="分类"
          name="category"
          :labelCol="{ span: 5 }"
        >
          <a-select
            v-model:value="goods.category"
            size="large"
            style="width: 258px"
            :options="categorys"
          ></a-select>
        </a-form-item>
        <a-form-item
          style="margin-top: 30px"
          ref="brand"
          label="品牌"
          name="brand"
          :labelCol="{ span: 5 }"
        >
          <a-select
            v-model:value="goods.brand"
            size="large"
            style="width: 258px"
            :options="brands"
          ></a-select>
        </a-form-item>
        <a-form-item
          style="margin-top: 30px"
          ref="status"
          label="状态"
          name="status"
          :labelCol="{ span: 7 }"
        >
          <a-radio-group v-model:value="goods.status">
            <a-radio value="上架">上架</a-radio>
            <a-radio value="下架">下架</a-radio>
          </a-radio-group>
        </a-form-item>
        <a-form-item
          style="margin-top: 30px"
          ref="image"
          label="商品主图"
          name="image"
          :labelCol="{ span: 18 }"
        >
          <a-upload-dragger
            v-model:file-list="fileList"
            name="image"
            list-type="picture-card"
            class="avatar-uploader"
            :show-upload-list="false"
            :customRequest="customRequest"
            :before-upload="beforeUpload"
          >
            <img
              style="height: 200px; width: 250px; border-radius: 10px"
              v-if="goods.image"
              :src="goods.image"
              alt="avatar"
            />
            <div v-else>
              <loading-outlined v-if="loading"></loading-outlined>
              <plus-outlined v-else></plus-outlined>
              <div class="ant-upload-text">上传</div>
            </div>
          </a-upload-dragger>
        </a-form-item>
      </a-form>

      <!-- 富文本 -->
      <div style="margin-top: 20px">商品详情</div>
      <div style="border: 1px solid #ccc; margin-top: 20px">
        <Toolbar
          style="border-bottom: 1px solid #ccc"
          :editor="editorRef"
          :defaultConfig="toolbarConfig"
          :mode="mode"
        />
        <Editor
          style="height: 500px; overflow-y: hidden"
          v-model="goods.detail"
          :defaultConfig="editorConfig"
          :mode="mode"
          @onCreated="handleCreated"
        />
      </div>

      <div
        style="
          display: flex;
          justify-content: flex-end;
          align-items: center;
          height: 50px;
          margin-top: 20px;
          width: 78%;
        "
      >
        <a-button type="primary" ghost @click="save">保存</a-button>
        <a-button style="margin-left: 10px" @click="handleCancel"
          >取消</a-button
        >
      </div>
    </a-card>
  </div>
</template>

<script setup>
import { ArrowLeftOutlined } from "@ant-design/icons-vue";
import { ref, onMounted, onBeforeUnmount, shallowRef } from "vue";
import { Editor, Toolbar } from "@wangeditor/editor-for-vue";
import { upload } from "@/api/upload";
import { message } from "ant-design-vue";
import {
  saveBusiness,
  echo,
  update,
  getBrand,
  getCategory,
  getStores,
} from "@/api/goods";
import router from "@/router";
import { useAdminStore } from "@/stores/admin";
import { useRoute } from "vue-router";

const route = useRoute();
const isEdit = ref(false);
const goodsId = ref(null);
goodsId.value = route.query.id;
isEdit.value = route.query.isEdit;
const goods = ref({
  key: null,
  name: "",
  brand: "",
  category: "",
  price: null,
  status: "",
  image: "",
  number: null,
  detail: "",
  store: "",
  unit: "",
});

const stores = ref([]);
const brands = ref([]);
const categorys = ref([]);
const adminStore = useAdminStore();
onMounted(() => {
  //获取商品品牌
  getBrand().then((res) => {
    if (res.code === 200) {
      brands.value = res.data;
    }
  });
  //获取商品分类
  getCategory().then((res) => {
    if (res.code === 200) {
      categorys.value = res.data;
    }
  });
  //获取商品店铺
  getStores(adminStore.admin.key).then((res) => {
    if (res.code === 200) {
      stores.value = res.data;
    }
  });

  if (isEdit.value) {
    echoGoods();
  }
});

// 编辑器实例，必须用 shallowRef
const editorRef = shallowRef();

const toolbarConfig = {};
const editorConfig = { MENU_CONF: {} };
editorConfig.placeholder = "请输入内容.......";
//富文本上传图片接口
editorConfig.MENU_CONF["uploadImage"] = {
  fieldName: "file",
  server: "http://localhost:9800/common/editor/upload",
};

// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
  const editor = editorRef.value;
  if (editor == null) return;
  editor.destroy();
});

const handleCreated = (editor) => {
  editorRef.value = editor; // 记录 editor 实例，重要！
};

//商品回显
function echoGoods() {
  echo(goodsId.value).then((res) => {
    if (res.code === 200 && res.data != null) {
      goods.value = res.data;
    }
  });
}

//头像上传部分
const fileList = ref([]);
function customRequest(file) {
  upload(file).then((res) => {
    if (res.code === 200) {
      goods.value.image = res.data;
    }
  });
}

const beforeUpload = (file) => {
  const isJpgOrPng = file.type === "image/jpeg" || file.type === "image/png";
  if (!isJpgOrPng) {
    message.error("限定上传jpg/png格式!");
  }
  const isLt2M = file.size / 1024 / 1024 < 2;
  if (!isLt2M) {
    message.error("文件大于2MB!");
  }
  return isJpgOrPng && isLt2M;
};

//新增商品操作
function save() {
  formRef.value
    .validate()
    .then(() => {
      if (goods.value.detail === "") {
        message.error("请输入商品详情！");
      } else {
        //新增商品
        if (goods.value.key === null) {
          saveBusiness(goods.value).then((res) => {
            if (res.code === 200) {
              message.success("新增成功！");
              //重新加载商品数据
              goods.value = {};
              goods.value.key = null;
              router.push("/goods");
            }
          });
        } else {
          //修改商品
          update(goods.value).then((res) => {
            if (res.code === 200) {
              message.success("修改成功！");
              //重新加载商品数据
              goods.value = {};
              router.push("/goods");
            }
          });
        }
      }
    })
    .catch((error) => {
      console.log("error", error);
    });
}

//取消新增商品操作
function handleCancel() {
  router.push("/goods");
  goods.value = {};
}

function backToGoods() {
  router.push("/goods");
}

//数据校验
const formRef = ref();
// const labelCol = {
//   span: 13,
// };
// const wrapperCol = {
//   span: 22,
// };
const rules = {
  name: [
    {
      required: true,
      message: "请输入商品名",
      trigger: "change",
    },
  ],
  unit: [
    {
      required: true,
      message: "请输入商品计件单位",
      trigger: "change",
    },
  ],
  number: [
    {
      required: true,
      message: "请输入商品数量",
      trigger: "change",
    },
  ],
  brand: [
    {
      required: true,
      message: "请选择商品所属品牌",
      trigger: "change",
    },
  ],
  category: [
    {
      required: true,
      message: "请选择商品所属分类",
      trigger: "change",
    },
  ],
  introduce: [
    {
      required: true,
      message: "请输入商品介绍",
      trigger: "change",
    },
  ],
  status: [
    {
      required: true,
      message: "请选择商品状态",
      trigger: "blur",
    },
  ],
  image: [
    {
      required: true,
      message: "请上传商品图",
      trigger: "blur",
    },
  ],
  imageOne: [
    {
      required: true,
      message: "请上传商品图",
      trigger: "blur",
    },
  ],
  imageTwo: [
    {
      required: true,
      message: "请上传商品图",
      trigger: "blur",
    },
  ],
  imageThree: [
    {
      required: true,
      message: "请上传商品图",
      trigger: "blur",
    },
  ],
  imageFour: [
    {
      required: true,
      message: "请上传商品图",
      trigger: "blur",
    },
  ],
  store: [
    {
      required: true,
      message: "请选择商品所属店铺",
      trigger: "blur",
    },
  ],
  price: [
    {
      required: true,
      message: "请输入商品单价",
      trigger: "blur",
    },
  ],
};
</script>

<style scoped>
.options {
  margin-top: 10px;
}

.table {
  margin-top: 10px;
}

.avatar-uploader > .ant-upload {
  width: 50px;
  height: 50px;
}
.ant-upload-select-picture-card i {
  font-size: 32px;
  color: #999;
}

.ant-upload-select-picture-card .ant-upload-text {
  margin-top: 8px;
  color: #666;
}
.paginAtion {
  padding-top: 20px;
  padding-left: 310px;
  margin-bottom: 20px;
}
</style>>